<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="日期" prop="courseDate">
        <el-date-picker clearable
                        v-model="queryParams.courseDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="讲师" prop="teacherName">
        <el-input
          v-model="queryParams.teacherName"
          placeholder="请输入讲师名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['teaching:curriculum:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['teaching:curriculum:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['teaching:curriculum:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['teaching:curriculum:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-row>
      <el-col :span="4">
        <div style="height: 60px;background-color: #F8F8F9;border: 1px #DFE6EC solid">
          <el-input
            style="width: 90%;margin: 10px"
            placeholder="输入关键字进行过滤"
            prefix-icon="el-icon-search"
            v-model="filterText">
          </el-input>
        </div>
        <div>
          <el-tree
            class="filter-tree"
            :data="data"
            :props="defaultProps"
            node-key="id"
            default-expand-all
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
            ref="tree">
          </el-tree>
        </div>
      </el-col>
      <el-col :span="20">
        <el-table v-loading="loading" :data="curriculumList" border
                  @selection-change="handleSelectionChange">
          <el-table-column label="序号" align="center" type="index" width="50">
          </el-table-column>
          <el-table-column label="班级名" align="center" prop="className"/>
          <el-table-column label="日期" align="center" prop="courseDate" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.courseDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="星期几" align="center" prop="weekDay"/>
          <el-table-column label="内容" align="center" prop="content"/>
          <el-table-column label="讲师名" align="center" prop="teacherName"/>
          <el-table-column label="备注" align="center" prop="reamark"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['teaching:curriculum:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['teaching:curriculum:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课表 管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班级名" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名"/>
        </el-form-item>
        <el-form-item label="日期" prop="courseDate">
          <el-date-picker clearable
                          v-model="form.courseDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="星期几" prop="weekDay">
          <el-input v-model="form.weekDay" placeholder="请输入星期几"/>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="form.content" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="讲师名" prop="teacherName">
          <el-input v-model="form.teacherName" placeholder="请输入讲师名"/>
        </el-form-item>
        <el-form-item label="备注" prop="reamark">
          <el-input v-model="form.reamark" placeholder="请输入备注"/>
        </el-form-item>
        <el-form-item label="校区id" prop="campusId">
          <el-input v-model="form.campusId" placeholder="请输入校区id"/>
        </el-form-item>
        <el-form-item label="校区名" prop="campusName">
          <el-input v-model="form.campusName" placeholder="请输入校区名"/>
        </el-form-item>
        <el-form-item label="学科名" prop="subjectName">
          <el-input v-model="form.subjectName" placeholder="请输入学科名"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport"/>
          是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCurriculum,
  getCurriculum,
  delCurriculum,
  addCurriculum,
  updateCurriculum,
  getCurriculumList
} from "@/api/teaching/curriculum";
import {parseTime} from "../../../utils/ruoyi";
import {getToken} from "@/utils/auth";
// 导入模板接口importTemplate
import {importTemplate} from "@/api/system/user";
import Template from "../../performance/template/index.vue";
import {listCampus} from "../../../api/teacher/teacher";


export default {
  name: "Curriculum",
  components: {Template},
  data() {
    return {
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/teaching/curriculum/importData"
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课表 管理表格数据
      curriculumList: [],
      campus: [],
      campusName: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classId: null,
        className: null,
        courseDate: null,
        weekDay: null,
        content: null,
        teacherId: null,
        teacherName: null,
        reamark: null,
        deleted: null,
        campusId: null,
        campusName: null,
        subjectId: null,
        subjectName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      options: {
        importUrl: "/teaching/curriculum" + "/importData",
        columns: [{
          field: 'className',
          title: '班级名'
        },
          {
            field: 'courseDate',
            title: '日期'
          },
          {
            field: 'weekDay',
            title: '星期几'
          }, {
            field: 'content',
            title: '内容'
          }, {
            field: 'courseDate',
            title: '日期'
          }, {
            field: 'teacherName',
            title: '讲师名'
          }, {
            field: 'reamark',
            title: '备注'
          }]
      },
      filterText: '',
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label',
        id: 'id'
      },
      courseInfo:[]
    };
  },
  created() {
    this.getList();

  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
      console.log(val)
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    findAllParentsById(id, nodes = this.data, parents = []) {
      for (const node of nodes) {
        if (Array.isArray(node.children) && node.children.length > 0) {
          const foundInChildren = this.findAllParentsById(id, node.children, [...parents, node]);
          if (foundInChildren.length > 0) {
            return foundInChildren;
          }
        }
        if (node.id === id) {
          return [...parents, node];
        }
      }
      return parents;
    },
    handleNodeClick(node) {
      const targetNodeId = node.id; // 替换为你想查询的目标节点ID
      const parents = this.findAllParentsById(targetNodeId);

      if (parents.length > 0) {
        console.log('Parent Nodes:');
        parents.forEach((parent, index) => {
          console.log(`Level ${index + 1}:`, parent.label);
          this.courseInfo.push(parent.label);
        });
        console.log(this.courseInfo);
        this.queryParams.campusName = this.courseInfo[0];
        this.queryParams.subjectName = this.courseInfo[1];
        this.queryParams.className = this.courseInfo[2];
        listCurriculum(this.queryParams).then(response=>{
          this.curriculumList = response.rows;
          this.total = response.total;
        });
        this.courseInfo = [];
      } else {
        console.log('Target node not found');
      }
    },
    parseTime,
    /** 查询课表 管理列表 */
    getList() {
      this.loading = true;
      listCurriculum(this.queryParams).then(response => {
        this.curriculumList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      getCurriculumList().then(response => {
        this.data = response.data
        console.log(this.data)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        classId: null,
        className: null,
        courseDate: null,
        weekDay: null,
        content: null,
        teacherId: null,
        teacherName: null,
        reamark: null,
        deleted: null,
        campusId: null,
        campusName: null,
        subjectId: null,
        subjectName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
          pageSize: 10,
          classId: null,
          className: null,
          courseDate: null,
          weekDay: null,
          content: null,
          teacherId: null,
          teacherName: null,
          reamark: null,
          deleted: null,
          campusId: null,
          campusName: null,
          subjectId: null,
          subjectName: null
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课表 管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCurriculum(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改课表 管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCurriculum(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCurriculum(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除课表 管理编号为"' + ids + '"的数据项？').then(function () {
        return delCurriculum(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('teaching/curriculum/export', {
        ...this.queryParams
      }, `curriculum_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
// 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
